//
//  NetworkTools.swift
//  MyWeibo
//
//  Created by cat on 15/7/31.
//  Copyright © 2015年 cat. All rights reserved.
//

import UIKit
import AFNetworking

/// 错误的类型标记
private let XBXErrorDomainName = "com.xbxcat.error"

/// 错误枚举
private enum XBXNetworkError: Int {
    case emptyDataError = -1
    case emptyTokenError = -2
    
    /// 错误描述
    private var errorDescrption: String {
        switch self {
        case .emptyDataError: return "空数据"
        case .emptyTokenError: return "Token 为空"
        }
    }
    
    /// 根据枚举类型,返回对应错误
    private func error() -> NSError {
        return NSError(domain: XBXErrorDomainName, code: rawValue, userInfo: [XBXErrorDomainName: errorDescrption])
    }
}

/// 网络访问方法
private enum XBXNetworkMethod: String {
    case GET = "GET"
    case POST = "POST"
}

class NetworkTools: AFHTTPSessionManager {
 
    
    // 应用信息
    private let clientId = "2253765155"
    private let appSecret = "ac8121f7e80f90e1fdc731c83cdf6a24"
    /// 回调地址
    let redirectUrl = "http://www.baidu.com"
    
    // MARK: - 加载微博数据
    func loadStatus(since_id: Int, max_id: Int, finished: XBXNetFinishedCallBack) {
        //判断token是否存在
        guard var params = tokenDict(finished) else {
            
            return
        }
        if since_id > 0 {
            params["since_id"] = since_id
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        // params有值
        let urlString = "2/statuses/home_timeline.json"
        request(XBXNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
        
    }
    
    // MARK - 加载用户数据
    func loadUserInfo(uid: String, finished: XBXNetFinishedCallBack) {
        
        guard var params = tokenDict(finished) else {
            return
        }
        let urlString = "2/users/show.json"
        params["uid"] = uid
        
        // 发送网络请求
        request(XBXNetworkMethod.GET, urlString: urlString, params: params, finished: finished)
    }

    // MARK: - OAuth授权
    /// 返回OAuth授权地址
    func oauthUrl() -> NSURL {
        let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUrl)"
        
        return NSURL(string: urlString)!
    }
    
    /// 加载Token
    func loadAccessToken(code: String, finished:XBXNetFinishedCallBack) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUrl]
       request(XBXNetworkMethod.POST, urlString: urlString, params: params, finished: finished)
        
    }
    
    // 检查并生成token字典
    private func tokenDict(finished: XBXNetFinishedCallBack) -> [String: AnyObject]? {
        // 判断token 是否存在
        if UserAccount.sharedAccount?.access_token == nil {
            // 错误回调,token 为空
            let error = XBXNetworkError.emptyTokenError.error()
            print(error)
            finished(result: nil, error: error)
            
            return nil
        }
        
        return ["access_token": UserAccount.sharedAccount!.access_token!]
    }
    
    // MARK: - 类型定义
    
    typealias XBXNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?) -> ()
    
    static let sharedTools: NetworkTools = {
        let baseURL = NSURL(string: "https://api.weibo.com/")
        let tools = NetworkTools(baseURL: baseURL)
        
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain") as Set<NSObject>
        
        return tools
    }()
    
    // MARK: - 封装网络方法
    
    private func request(method: XBXNetworkMethod, urlString: String, params:[String: AnyObject], finished: XBXNetFinishedCallBack) {
        
        // 1.成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) ->Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                
                finished(result: result, error: nil)
            } else {
                // 没有错误
                print("没有错误 \(method) Request \(urlString)")
                
                finished(result: nil, error: XBXNetworkError.emptyDataError.error())
            }
        }
        // 2.定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error)-> Void in
            print(error)
            
            finished(result: nil, error: error)
            
        }
        
        // 3. 根据 method来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }
}
